package cn.itcast.bos.service.realm;

import java.util.List;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import cn.itcast.bos.domain.system.Permission;
import cn.itcast.bos.domain.system.Role;
import cn.itcast.bos.domain.system.User;
import cn.itcast.bos.service.system.PermissionService;
import cn.itcast.bos.service.system.RoleService;
import cn.itcast.bos.service.system.UserService;

//@Service
public class UserRealm extends AuthorizingRealm{
	
	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private PermissionService permissionService;
	private Logger logger = Logger.getLogger(User.class);

	/*
	 * 授权(non-Javadoc)理解AuthorizationInfo
	 * @see org.apache.shiro.realm.AuthorizingRealm#doGetAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection pc) {
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		//查询用户的角色
		Subject subject = SecurityUtils.getSubject();
		User user = (User) subject.getPrincipal();
		List<Role> roles = roleService.findByUser(user);
		for(Role role : roles){
			authorizationInfo.addRole(role.getKeyword());
		}
		//查询权限
		List<Permission> permissions = permissionService.findByUser(user);
		for(Permission permission : permissions){
			authorizationInfo.addStringPermission(permission.getKeyword());
		}
		logger.info(user.getUsername()+"用户授权成功");
		return authorizationInfo;
	}

	//认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken usernamepasswordToken = (UsernamePasswordToken) token;
		//根据名称查询对象
		User user = userService.findByUserName(usernamepasswordToken.getUsername());
		if(user == null){
			//查询不到指定用户
			return null;
		}else{
			logger.info(user.getUsername()+":"+user.getPassword()+"用户认证成功");
			//当返回用户名和密码时，配置文件中注入的securityManager自动比较密码是否相同
			//如果匹配成功则跳转，如果不成功就报密码错误-----------------getName()
			return new SimpleAuthenticationInfo(user,user.getPassword(),getName());
		}
		
		
	}

}
